<!-- app1/public/index.html -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>应用1 - 单点登录示例</title>
  <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen">
  <header class="bg-white shadow">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
      <h1 class="text-xl font-bold text-gray-900">应用1</h1>
      <button id="logoutBtn" class="text-sm text-indigo-600 hover:text-indigo-900">登出</button>
    </div>
  </header>

  <main class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
    <div id="loading" class="text-center">加载中...</div>
    <div id="unauthorized" class="hidden text-center">
      <p class="text-gray-500">您尚未登录，请先登录</p>
      <button id="loginBtn" class="mt-4 px-4 py-2 bg-indigo-600 text-white rounded">前往登录</button>
    </div>
    <div id="userInfo" class="hidden">
      <h2 class="text-2xl font-bold text-gray-900 mb-4">欢迎回来，<span id="username"></span>！</h2>
      <p class="text-gray-600 mb-6">您已通过单点登录验证，可访问以下资源：</p>
      <div class="bg-white p-6 rounded-lg shadow">
        <h3 class="text-lg font-medium text-gray-900 mb-2">应用1专属内容</h3>
        <ul class="list-disc pl-5 text-gray-600">
          <li>用户数据分析报表</li>
          <li>项目进度管理</li>
          <li>团队协作工具</li>
        </ul>
      </div>
      <div class="mt-6">
        <a href="http://localhost:3002" id="app2Link" 
           class="text-indigo-600 hover:text-indigo-900 font-medium">
          前往应用2（无需重新登录） →
        </a>
      </div>
    </div>
  </main>

  <script>
    // 从URL获取accessToken
    const urlParams = new URLSearchParams(window.location.search);
    let accessToken = urlParams.get('accessToken');
    const APP1_URL = 'http://localhost:3001';
    const AUTH_SERVER_URL = 'http://localhost:3000';
    const APP2_URL = 'http://localhost:3002';

    // 页面加载时验证登录状态
    async function checkLogin() {
      const loading = document.getElementById('loading');
      const unauthorized = document.getElementById('unauthorized');
      const userInfo = document.getElementById('userInfo');

      if (!accessToken) {
        // 没有token，尝试刷新token
        try {
          const res = await fetch(`${AUTH_SERVER_URL}/refresh-token`, {
            method: 'POST',
            credentials: 'include' // 携带refreshToken Cookie
          });
          if (res.ok) {
            const data = await res.json();
            accessToken = data.accessToken;
            // 刷新URL中的token
            window.history.replaceState(null, null, `${APP1_URL}?accessToken=${accessToken}`);
          } else {
            throw new Error('无有效会话');
          }
        } catch (err) {
          loading.classList.add('hidden');
          unauthorized.classList.remove('hidden');
          return;
        }
      }

      // 验证token有效性
      try {
        const res = await fetch(`${AUTH_SERVER_URL}/verify-token`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ token: accessToken })
        });

        if (!res.ok) throw new Error('token无效');
        const data = await res.json();
        
        // 显示用户信息
        document.getElementById('username').textContent = data.user.username;
        // 更新应用2链接（携带token）
        document.getElementById('app2Link').href = `${APP2_URL}?accessToken=${accessToken}`;
        
        loading.classList.add('hidden');
        userInfo.classList.remove('hidden');
      } catch (err) {
        loading.classList.add('hidden');
        unauthorized.classList.remove('hidden');
      }
    }

    // 登录按钮点击事件
    document.getElementById('loginBtn').addEventListener('click', () => {
      window.location.href = `${AUTH_SERVER_URL}/login?redirectUrl=${APP1_URL}`;
    });

    // 登出按钮点击事件
    document.getElementById('logoutBtn').addEventListener('click', async () => {
      await fetch(`${AUTH_SERVER_URL}/logout`, {
        method: 'POST',
        credentials: 'include'
      });
      window.location.href = APP1_URL; // 登出后刷新页面
    });

    // 页面加载时检查登录状态
    checkLogin();
  </script>
</body>
</html>